<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];

    require_once($rootDir.'/classes/SessionManager.class.php');
    require_once($rootDir.'/classes/db/SQLiteConnector.class.php');   
    require_once($rootDir.'/classes/db/LeproUserDAO.class.php');
    require_once($rootDir.'/classes/db/LeproBJGroupDAO.class.php');
    require_once($rootDir.'/classes/LeproBJAppSettings.class.php');
    
    $tUID = urldecode($_POST['uid']);
    $tGID = urldecode($_POST['gid']);
    $tACT = urldecode($_POST['act']);
    
    date_default_timezone_set('Europe/Moscow');

    if (SessionManager::isUserLoggedIn()) {
        $userId = SessionManager::getCurrentUserID();
        if (($userId != null) && ($tUID == $userId) && (preg_match("/^\d*$/", $tUID) > 0) 
            && SessionManager::isUserChecked($tUID)
            && ((strlen($tGID) == 0) || (preg_match("/^\d*$/", $tGID) > 0)) 
            && (preg_match("/^(create|join|leave|try-leave|error)$/", $tACT) > 0)) {
            $connector = SQLiteConnector::getInstance();
            if ($connector->connect()) { // connect to DB
                $userDAO = new LeproUserDAO($connector->getDB());
                $groupDAO = new LeproBJGroupDAO($connector->getDB()); 
                $user = $userDAO->load($userId); // try to load this user from DB
                if ($user != null) {
                    $weekDay = date("w");
                    $actAllowed = false;
                    $group = null;
                    switch ($tACT) {
                        case 'create': {
                            $actAllowed = (strlen($tGID) == 0) && ($user->inGroup($tGID) === false);
                            $actAllowed = $actAllowed && ($groupDAO->userGroupsCount($userId) == 0);
                        } break;
                        case 'join': {
                            $actAllowed = ((int)$tGID <= $groupDAO->getCount()) && ($user->inGroup($tGID) === false);
                            $group = $groupDAO->load($tGID);
                        } break;
                        case 'leave': case 'try-leave': {
                            $actAllowed = in_array($weekDay, LeproBJAppSettings::$LALLOWED_DAYS) && 
                                          ($user->inGroup($tGID) !== false);
                            $group = $groupDAO->load($tGID);
                        } break;
                        /* case 'error': {
                        } break; */                        
                    } 
                    echo ($actAllowed ? '1' : '0').(($group != null) ? ($group->isProtected() ? '1' : '0') : '-').$tACT[0];
                } else echo ':(';
            }
        } else echo ':(';
    }

?>
